<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ page.total }}条记录</span>
        <template slot="after">
          <el-button type="success" size="small" @click="$router.push('/import')">导入Excel</el-button>
          <el-button type="danger" size="small" @click="exportData">导出Excel</el-button>
          <el-button type="primary" size="small" :disabled="!checkPermission('POINT-USER-ADD')" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 表格 -->
      <el-card v-loading="loading">
        <el-table border :data="list" style="width: 100%">
          <el-table-column align="center" sortable label="序号" type="index" />
          <el-table-column align="center" sortable label="姓名" prop="username" />
          <el-table-column align="center" sortable label="头像">
            <template v-slot="{ row }">
              <img
                v-imagError="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto"
                style="border-radius: 50%; width: 100px; height: 100px; padding: 10px"
                @click="showQrCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column align="center" sortable label="工号" prop="workNumber" />
          <!-- formatter格式化内容 -->
          <el-table-column
            align="center"
            sortable
            label="聘用形式"
            :formatter="getFormatter"
            prop="formOfEmployment"
          />
          <el-table-column align="center" sortable label="部门" prop="departmentName" />
          <el-table-column align="center" sortable label="入职时间">
            <!-- 时间格式化 -->
            <template slot-scope="{ row }">{{ row.timeOfEntry | formatDate }}</template>
          </el-table-column>
          <el-table-column align="center" sortable label="账户状态" prop="enableState">
            <template slot-scope="{ row }">
              <!-- 根据当前状态 是否打开开关 -->
              <el-switch
                :value="row.enableState === 1"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
            </template>
          </el-table-column>
          <el-table-column align="center" sortable label="操作" fixed="right" width="280">
            <template slot-scope="{ row }">
              <!-- <span>{{ row }}</span> -->
              <el-button type="text" size="small" :disabled="!checkPermission('POINT-USER-UPDATE')" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="character(row.id)">角色</el-button>
              <el-button type="text" size="small" :disabled="!checkPermission('point-user-delete')" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <!-- 分页 -->
      <el-row type="flex" justify="center" align="middle" style="height: 60px">
        <el-pagination
          layout=" prev, pager, next"
          :current-page="page.page"
          :page-size="page.size"
          :total="page.total"
          @current-change="changePage"
        />
      </el-row>
    </div>
    <!-- 新增员工弹窗 -->
    <add-employee :show-dialog.sync="showDialog" />
    <!-- 二维码弹窗 -->
    <el-dialog title="二维码" :visible.sync="showCodeDialog">
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>
    <!-- 分配角色弹窗 -->
    <assign-role ref="roleRef" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import employees from '@/api/constant/employees'
import addEmployee from './components/add-employee'
import assignRole from './components/assign-role'
import { formatDate } from '@/filters'
import qrCode from 'qrcode'

export default {
  // 组件名称
  name: '',
  // 局部注册的组件
  components: {
    addEmployee, assignRole
  },
  // 组件参数 接收来自父组件的数据
  props: {},
  // 组件状态值
  data() {
    return {
      loading: false,
      list: [], // 员工综合数据
      page: {
        page: 1, // 当前页码
        size: 10,
        total: 0 // 总数
      },
      showDialog: false, // 弹窗的显示与隐藏
      showCodeDialog: false, // 二维码显示与隐藏
      showRoleDialog: false, // 角色显示与隐藏
      userId: null
    }
  },
  // 计算属性
  computed: {},
  // 侦听器
  watch: {},
  created() {
    this.getEmployeeList()
  },
  // 组件方法
  methods: {
    // 二维码
    showQrCode(url) {
      if (url) {
        this.showCodeDialog = true
        // 将回调延迟到下次 DOM 更新循环之后执行。在修改数据之后立即使用它，然后等待 DOM 更新。
        this.$nextTick(() => {
          qrCode.toCanvas(this.$refs.myCanvas, url)
        })
      } else {
        this.$message.warning('该用户还未上传头像')
      }
    },
    // 获取员工综合数据
    async getEmployeeList() {
      this.loading = true
      const result = await getEmployeeList(this.page)
      this.list = result.rows
      this.page.total = result.total
      this.loading = false
    },
    changePage(newPage) {
      this.page.page = newPage
      this.getEmployeeList()
    },
    // 格式化聘用形式 // 见element ui
    getFormatter(row, column, cellValue, index) {
      // row当前数据
      // console.log(cellValue);
      // cellValue当前表格内容
      const obj = employees.hireType.find(item => item.id === cellValue) // 返回当前查找到的数据
      return obj ? obj.value : '未知'
    },
    // 删除员工
    async delEmployee(id) {
      await this.$confirm('确定要删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      await delEmployee(id)
      this.getEmployeeList()
      this.$message.success('删除成功！')
    },
    // 导出excel
    exportData() {
      //  做操作
      // 表头对应关系
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 复杂表头
      const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
      // 表格合并
      const merges = ['A1:A2', 'B1:F1', 'G1:G2']
      // 懒加载
      import('@/vendor/Export2Excel').then(async excel => {
        const { rows } = await getEmployeeList({ page: 1, size: this.page.total })
        const data = this.formatJson(headers, rows)

        excel.export_json_to_excel({
          header: Object.keys(headers),
          data,
          filename: '员工信息表',
          autoWidth: true,
          bookType: 'xlsx',
          multiHeader,
          merges
        })
      })
    },
    // 该方法负责将数组转化成二维数组
    formatJson(headers, rows) {
      // 首先遍历数组
      // [{ username: '张三'},{},{}]  => [[’张三'],[],[]]
      return rows.map(item => {
        return Object.keys(headers).map(key => {
          if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
            return formatDate(item[headers[key]]) // 返回格式化之前的时间
          } else if (headers[key] === 'formOfEmployment') {
            var en = employees.hireType.find(obj => obj.id === item[headers[key]])
            return en ? en.value : '未知'
          }
          return item[headers[key]]
        }) // => ["张三", "13811"，"2018","1", "2018", "10002"]
      })
      // return data
      // return rows.map(item => {
      //   // item是对象  => 转化成只有值的数组 => 数组值的顺序依赖headers  {username: '张三'  }
      //   // Object.keys(headers)  => ["姓名", "手机号",...]
      //   return Object.keys(headers).map(key => {
      //     return item[headers[key]]
      //   }) // /  得到 ['张三'，’129‘，’dd‘,'dd']
      // })
    },
    // 点击角色
    character(id) {
      this.showRoleDialog = true
      this.userId = id
      this.$refs.roleRef.getUserDetailById(id)
    }
  }
}
</script>

<style scoped lang="less"></style>
